/*
 * @Author: 脉迈
 * @Date: 2021-10-28 17:20:50
 * @LastEditors: 脉迈
 * @LastEditTime: 2022-01-25 13:11:18
 */
const PSD = require('psd');
const Path = require('path');
module.exports = app => ({
  async index (ctx,next) {
		let {request} = ctx;
		let {$helper,$config} = app
    let file = ctx.request.files.file;
		let psd = await PSD.open(file.path)
		let timeStr = + new Date();
		let descendantsList = psd.tree().descendants();
		descendantsList.reverse();
		let psdSourceList = []
		let currentPathDir = `/resource/upload_psd/${timeStr}`
		// 判断文件夹是否存在不存在则新建一个
		await $helper.dirExists(Path.join(__dirname, '../public' + currentPathDir));
		// 遍历图层
		for (var i = 0; i < descendantsList.length; i++){
			if (descendantsList[i].isGroup()) continue;
			if (!descendantsList[i].visible) continue;
			try{
			
				await descendantsList[i].saveAsPng(Path.join(__dirname, '../public' + currentPathDir + `/${i}.png`))
				let type = descendantsList[i].export().text? 'blockImage': 'blockImage'
				let imageSrc = `${$config.staticHost}${currentPathDir}/${i}.png`
				psdSourceList.push({
					...descendantsList[i].export(),
					type,
					imageSrc,
				})
			}catch (e) {
				// 转换不出来的图层先忽略
				continue;
			}
			
		}
		ctx.body = {
			elements: psdSourceList,
			document: psd.tree().export().document
		}
		
	},
	action(ctx, next){
		ctx.body = 'Hello World!';
	}
})
